package com.iweb.controller;

import com.common.context.RequestMapping;
import com.iweb.pojo.User;
import com.iweb.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 视图渲染 返回值 是 string
 * void 是 ajax
 */
@RequestMapping("user")
public class UserController {
    @RequestMapping("reg")
    public synchronized String Register(User user, HttpServletRequest request) {
        UserService userService = new UserService();
        boolean flag = userService.addUser(user);
        //如果flag为true，则用户不重复，
        if (flag) {
            //TO DO


            return "/user/login.jsp";


        } else {
            request.setAttribute("message", "用户已存在");
            return "/user/reg.jsp";
        }
    }


    @RequestMapping("login")
    public String login(User user, HttpServletRequest request) {
        UserService userService = new UserService();
        User result = userService.findByUserId(user.getUserid());
        // 业务用户
        if (result == null) {
            request.setAttribute("message", "用户不存在");
            return "/user/login.jsp";
        }
        // 判断密码
        if (!user.getPassword().equals(result.getPassword())) {
            request.setAttribute("message", "密码错误");
            return "/user/login.jsp";
        }
        // 保存用户到session
        HttpSession session = request.getSession();
        session.setAttribute("user", result);
        return "/user/homepage.jsp";
    }
}
